//
//  LSZGoAnswerTheQuestionsViewController.m
//  PartyClassCloud
//
//  Created by 梁素珍 on 2018/9/4.
//  Copyright © 2018年 九酷. All rights reserved.
//

#import "LSZGoAnswerTheQuestionsViewController.h"

@interface LSZGoAnswerTheQuestionsViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    UIView *  viewBackPop;
    UIView * viewWhite;
}
@property(nonatomic,strong) LSZAnswerQuestionsDetailsManager * answerQuestionsDetailsManager;
@property(nonatomic,strong) UICollectionView * collectionAnswer;
@property(nonatomic,strong) UICollectionViewFlowLayout * layout;
@property(nonatomic,strong) NSIndexPath * indexPathNow;//当前的位置
@property(nonatomic,strong) LSZAnswerPopup * answerPopup;//弹窗
@end

@implementation LSZGoAnswerTheQuestionsViewController
-(void)getDataAnswer
{
    [LSZRequestDicData getForQuestions:self.id_Id :^(BOOL isOk, NSString * string, LSZAnswerQuestionsDetailsManager * manager) {
        if (isOk == YES) {
            self.answerQuestionsDetailsManager = manager;
            [self addCountdown:(int)manager.arrayData.count];
            [self.collectionAnswer reloadData];
        }else{
            if ([string isEqualToString:@"重复登录"]) {
                [LSZPublicClassDataToll RepeatLoginInterfaceJump:self.view fromVC:@"LSZGoAnswerTheQuestionsViewController"];
            }else{
                [LSZPublicClassDataToll initWithAlertKuangView:self.view string:string];
            }
        }
    }];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.answerPopup removeFromSuperview];
}
-(void)goToLogin
{
    [LSZPublicClassDataToll goToLogin];
}
-(void)addNotificationCenter
{
    NSString * strDelete = [NSString stringWithFormat:@"%@Login",@"LSZGoAnswerTheQuestionsViewController"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goToLogin) name:strDelete object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"答题详情";
    [self addNotificationCenter];
    [self getDataAnswer];
    [self prepareLayout];
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"答题详情"] style:UIBarButtonItemStylePlain target:self action:@selector(clickAnswerDetails)];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickAnswerQuestions:) name:@"answerQuestions" object:nil];;
}
- (void)prepareLayout {
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    self.layout .scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.layout .itemSize = CGSizeMake(ScreenWidth, ScreenHeight - NAVIGATION_BAR_HEIGHT - 50);
    self.collectionAnswer = [[UICollectionView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, ScreenHeight - NAVIGATION_BAR_HEIGHT - 50-HOME_INDICATOR_HEIGHT) collectionViewLayout:self.layout];
    self.collectionAnswer.showsVerticalScrollIndicator = NO;
    self.collectionAnswer.showsHorizontalScrollIndicator = NO;
    self.collectionAnswer.delegate = self;
    self.collectionAnswer.dataSource = self;
    self.collectionAnswer.pagingEnabled = YES;
    self.collectionAnswer.bounces = YES;
    self.collectionAnswer.backgroundColor = RGBColor(236, 236, 236);
    [self.collectionAnswer registerClass:[LSZAnswerCollectionViewCell class] forCellWithReuseIdentifier:@"LSZAnswerCollectionViewCell"];
    [self.view addSubview:self.collectionAnswer];
    
    UIView * viewLow = [[UIView alloc]init];
    viewLow.userInteractionEnabled = YES;
    viewLow.backgroundColor = [UIColor whiteColor];
    viewLow.frame = CGRectMake(0, ScreenHeight-50-HOME_INDICATOR_HEIGHT, ScreenWidth, 50+HOME_INDICATOR_HEIGHT);
    [self.view addSubview:viewLow];
    UIButton * butLow = [[UIButton alloc]init];
    butLow.frame = CGRectMake(0,0, ScreenWidth/5, 50);
    [butLow setImage:[UIImage imageNamed:@"上一题"] forState:UIControlStateNormal];
    [butLow addTarget:self action:@selector(clickBut) forControlEvents:UIControlEventTouchUpInside];
    [viewLow addSubview:butLow];
    
    UIButton * butLowOK = [[UIButton alloc]init];
    butLowOK.frame = CGRectMake(CGRectGetMaxX(butLow.frame),0,ScreenWidth -  ScreenWidth/5*2, 50);
    [butLowOK setTitleColor:titleColorLSZ forState:UIControlStateNormal];
    [butLowOK setTitle:@"立即提交" forState:UIControlStateNormal];
    [butLowOK addTarget:self action:@selector(clickButOk) forControlEvents:UIControlEventTouchUpInside];
    [viewLow addSubview:butLowOK];
    
    UIButton * butLowRight = [[UIButton alloc]init];
    butLowRight.frame = CGRectMake(CGRectGetMaxX(butLowOK.frame), 0, ScreenWidth/5, 50);
    [butLowRight setImage:[UIImage imageNamed:@"下一题"] forState:UIControlStateNormal];
    [butLowRight addTarget:self action:@selector(clickButRight) forControlEvents:UIControlEventTouchUpInside];
    [viewLow addSubview:butLowRight];
    
    UIView * viewLineOne = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth/5,1, 1, 49)];
    viewLineOne.backgroundColor =  RGBColor(212, 212, 212);
    [viewLow addSubview:viewLineOne];
    UIView * viewLineTwo = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth/5*4, 1, 1, 49)];
    viewLineTwo.backgroundColor = RGBColor(212, 212, 212);
    [viewLow addSubview:viewLineTwo];
    
}
#pragma mark - delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.answerQuestionsDetailsManager.arrayData.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LSZAnswerCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LSZAnswerCollectionViewCell" forIndexPath:indexPath];
    LSZAnswerQuestionsDetailsMg * mg = nil;
    mg = self.answerQuestionsDetailsManager.arrayData[indexPath.row];
    cell.numberRow = indexPath.row+1;
    cell.manager = mg;
    return cell;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
#pragma mark - button-click
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGPoint pInView = [self.view convertPoint:self.collectionAnswer.center toView:self.collectionAnswer];
    self.indexPathNow = [self.collectionAnswer indexPathForItemAtPoint:pInView];
}
#pragma mark - 上一个
-(void)clickBut
{
    NSLog(@"点击选择");
    if (self.indexPathNow.row > 0) {
        [self.collectionAnswer scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.indexPathNow.item - 1 inSection:self.indexPathNow.section] atScrollPosition:(UICollectionViewScrollPositionNone) animated:YES];
        self.indexPathNow = [NSIndexPath indexPathForItem:self.indexPathNow.item - 1 inSection:self.indexPathNow.section];
        [self.collectionAnswer reloadData];
    }else{
        [self initWithtring:@"已经是第一题了!"];
    }
}
#pragma mark - 下一个
-(void)clickButRight
{
    if (self.indexPathNow.row < self.answerQuestionsDetailsManager.arrayData.count - 1) {
        [self.collectionAnswer scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.indexPathNow.item + 1 inSection:self.indexPathNow.section] atScrollPosition:(UICollectionViewScrollPositionNone) animated:YES];
        self.indexPathNow = [NSIndexPath indexPathForItem:self.indexPathNow.item + 1 inSection:self.indexPathNow.section];
        [self.collectionAnswer reloadData];
    }else{
        [self initWithtring:@"已经是最后一题了!"];
    }
}
#pragma mark - 切换选择
-(void)clickAnswerQuestions:(NSNotification *)notification
{
    NSInteger row = [notification.userInfo[@"row"] integerValue];
    if(row != self.indexPathNow.row){
        self.indexPathNow = [NSIndexPath indexPathForItem:row inSection:0];
        [self.collectionAnswer scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:row inSection:self.indexPathNow.section] atScrollPosition:(UICollectionViewScrollPositionNone) animated:YES];
        [self.collectionAnswer reloadData];
    }
}
#pragma mark - 提交
-(void)clickButOk
{
    NSInteger isOrRightNumber = 0;//答对题的个数
    NSInteger notTheAnswer = 0;//打错的个数
    NSMutableArray * mutArrayWrong = [[NSMutableArray alloc]init];
    for (int i = 0; i<self.answerQuestionsDetailsManager.arrayData.count; i++) {
        LSZAnswerQuestionsDetailsMg * mg = nil;
        mg = self.answerQuestionsDetailsManager.arrayData[i];
        if ([mg.examType isEqualToString:@"1"]) {
            //从0开始的
            if (mg.number == [mg.answer integerValue]) {
                isOrRightNumber = isOrRightNumber +1;//答对了
            }else if(mg.number == -1){
//                [self initWithtring:[NSString stringWithFormat:@"第%ld题您还未答题,请答完题再提交!",(long)i+1]];
//                return;
                notTheAnswer = notTheAnswer+1;
            }
            else{
                [mutArrayWrong addObject:mg];
            }
        }else if ([mg.examType isEqualToString:@"0"]){
            if (mg.number == [mg.answer integerValue]) {
                isOrRightNumber = isOrRightNumber +1;//答对了
            }else if(mg.number == -1){
                notTheAnswer = notTheAnswer+1;
//                [self initWithtring:[NSString stringWithFormat:@"第%ld题您还未答题,请答完题再提交!",(long)i+1]];
//                return;
            }
            else{
                [mutArrayWrong addObject:mg];
            }
        }
        else{
            NSString * string = [[NSString alloc]init];
            NSArray *sortResultArr = [mg.addAnswerArray sortedArrayUsingSelector:@selector(compare:)];//倒叙
            for (int i=0; i<sortResultArr.count; i++) {
                if (i == 0) {
                    string = sortResultArr[i];
                }else{
                    string = [NSString stringWithFormat:@"%@,%@",string,sortResultArr[i]];
                }
            }
            
            if([mg.answer isEqualToString:string]){
                isOrRightNumber = isOrRightNumber +1;//答对了
            }else if (mg.addAnswerArray.count == 0){
                notTheAnswer = notTheAnswer+1;
//                [self initWithtring:[NSString stringWithFormat:@"第%ld题您还未答题,请答完题再提交!",(long)i+1]];
//                return;
            }
            else{
                [mutArrayWrong addObject:mg];
            }
        }
    }
    
    if(notTheAnswer == 0){
        NSLog(@"答错了%ld题",(long) mutArrayWrong.count);
        LSZAnswerParseViewController * VC = [[LSZAnswerParseViewController alloc]init];
        VC.totalNumber = self.answerQuestionsDetailsManager.arrayData.count;
        VC.rightNumber  = isOrRightNumber;
        VC.wrongNumber  =  VC.totalNumber - isOrRightNumber;
        VC.arrayMg = mutArrayWrong;
        VC.id_Id = self.id_Id;
        [self.navigationController pushViewController:VC animated:YES];
    }else{
         [self initWithtring:[NSString stringWithFormat:@"第%ld题您还未答题,请答完题再提交!",(long)notTheAnswer]];
    }
}
#pragma mark - 答题超时的弹窗
-(void)APopUpWindowOverTime
{
    viewBackPop = [[UIView alloc]init];
    viewBackPop.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    viewBackPop.backgroundColor = [UIColor blackColor];
    viewBackPop.alpha = 0.6;
    [self.view addSubview:viewBackPop];
    
    viewWhite = [[UIView alloc]init];
    viewWhite.frame = CGRectMake(20, (ScreenHeight-140)/2, ScreenWidth-40, 140);
    viewWhite.backgroundColor = [UIColor whiteColor];
    [viewWhite.layer setMasksToBounds:YES];
    [viewWhite.layer setCornerRadius:4];
    [self.view addSubview:viewWhite];
    
    UILabel * labelTitle = [[UILabel alloc]init];
    labelTitle.frame =  CGRectMake(20, 10,viewWhite.frame.size.width-40, 22);
    labelTitle.font = FONT_(16);
    labelTitle.textColor = titleColorLSZ;
    labelTitle.text = @"超时提醒";
    [viewWhite addSubview:labelTitle];
    
    UILabel * labelContent = [[UILabel alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(labelTitle.frame)+10, labelTitle.frame.size.width, 40)];
    labelContent.textColor = titleColorLSZ;
    labelContent.font = FONT_(14);
    labelContent.numberOfLines = 0;
    labelContent.text = @"很遗憾考试时间到了!";
    [viewWhite addSubview:labelContent];
    
    UILabel * labelOk = [[UILabel alloc]initWithFrame:CGRectMake(20, viewWhite.frame.size.height-50, viewWhite.frame.size.width-40, 40)];
    labelOk.text = @"结束";
    labelOk.userInteractionEnabled = YES;
    labelOk.font = FONT_(14);
    labelOk.textColor = themeColor;
    labelOk.textAlignment = NSTextAlignmentRight;
    [viewWhite addSubview:labelOk];
    viewWhite.userInteractionEnabled = YES;
    viewBackPop.userInteractionEnabled = YES;

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClickLabelOk)];
    [viewWhite addGestureRecognizer:tapGesture];
    
}
-(void)tapClickLabelOk
{
    [viewBackPop removeFromSuperview];
    [viewWhite removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)addCountdown:(int)count
{
    __block int timeout = 60*count; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            //            dispatch_release(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self APopUpWindowOverTime];
                self.title = @"";
            });
        }else{
            NSString *strTime = [[NSString alloc]init];
            int minutes = timeout / 60;
            int seconds = timeout % 60;
            if (seconds<10) {
                if(minutes<10){
                    strTime = [NSString stringWithFormat:@"00:0%ld:0%ld",(long)minutes,(long)seconds];
                }else{
                    strTime = [NSString stringWithFormat:@"00:%ld:0%ld",(long)minutes,(long)seconds];
                }
            }else{
                if(minutes<10){
                    strTime = [NSString stringWithFormat:@"00:0%ld:%ld",(long)minutes,(long)seconds];
                }else{
                    strTime = [NSString stringWithFormat:@"00:%ld:%ld",(long)minutes,(long)seconds];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                self.title = strTime;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
#pragma mark - 答题结果
-(void)clickAnswerDetails
{
    self.answerPopup = [[LSZAnswerPopup alloc]init];
    [self.answerPopup show];
    [self.answerPopup initWithAnswerPopup:self.answerQuestionsDetailsManager];
}
@end
